package pkg

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"log"
	"net/http"
)

func AuthToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		if token == "" {
			c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "token不能为空"})
			return
		}
		userId, err := ParseJwtToken(token)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "token解析失败"})
			return
		}
		c.Set("userId", userId)
		c.Next()
	}
}

func ParseJwtToken(tokenString string) (float64, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		return []byte("123456"), nil
	}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
	if err != nil {
		log.Fatal(err)
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok {
		return claims["userId"].(float64), err
	} else {
		fmt.Println(err)
	}
	return 0, nil
}
